<template>
  <div class="deposit-management">
    <div class="page-header">
      <h2>存款业务管理</h2>
      <div class="header-actions">
        <button @click="showAddModal = true" class="btn btn-primary">
          <span class="btn-icon">➕</span>
          新增存款业务
        </button>
        <button @click="exportToCSV" class="btn btn-secondary">
          <span class="btn-icon">📊</span>
          导出CSV
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索业务名称或描述..."
          class="search-input"
        />
        <button @click="searchDeposits" class="search-btn" :disabled="true">🔍</button>
      </div>
    </div>

    <!-- 存款业务列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>编号</th>
            <th>业务名称</th>
            <th>描述</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="deposit in filteredDeposits" :key="deposit.savingID">
            <td>{{ deposit.savingID }}</td>
            <td>{{ deposit.savingName }}</td>
            <td>{{ deposit.descrip }}</td>
            <td>
              <div class="action-buttons">
                <button @click="editDeposit(deposit)" class="btn-icon-btn" title="编辑">✏️</button>
                <button @click="deleteDeposit(deposit.savingID)" class="btn-icon-btn delete" title="删除">🗑️</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增/编辑存款业务模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑存款业务' : '新增存款业务' }}</h3>
          <button @click="closeModal" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="saveDeposit" class="modal-form">
          <div class="form-row">
            <div class="form-group" >
              <label>业务名称 *</label>
              <input v-model="depositForm.name" type="text" required />
            </div>
          </div>
          <div class="form-group">
            <label>业务描述</label>
            <textarea v-model="depositForm.description" rows="4" placeholder="请输入业务描述..."></textarea>
          </div>
          <div class="modal-actions">
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'DepositManagement',
  data() {
    return {
      deposits: [],
      searchQuery: '',
      statusFilter: '',
      showAddModal: false,
      showEditModal: false,
      depositForm: {
        name: '',
        description: '',
        interestRate: '',
        minAmount: '',
        status: 'active'
      },
      editingId: null,
      formData: {
        adminID: 10011001,
        adminName: "admin",
        adminPass: "10011001",
        savingID: '',
        savingName: '',
        descrip: '',
      }
    }
  },
  computed: {
    filteredDeposits() {
    // 获取原始存款数据
    let filtered = this.deposits;

    // 如果存在搜索查询，则根据查询内容过滤数据
    if (this.searchQuery) {
      const query = this.searchQuery.toLowerCase(); // 将查询转换为小写以支持大小写不敏感搜索
      filtered = filtered.filter((deposit) => {
        return (
          (deposit.savingID && deposit.savingID.toString().toLowerCase().includes(query)) || // 按编号搜索
          (deposit.savingName && deposit.savingName.toLowerCase().includes(query)) || // 按业务名称搜索
          (deposit.descrip && deposit.descrip.toLowerCase().includes(query)) // 按描述搜索
         );
        });
      }

      return filtered;
    }

  },
  mounted() {
    this.updateTime()
    this.refreshInterval = setInterval(this.updateTime, 1000)
  },
  methods: {
    async updateTime() {
      console.log(this.formData)
      try {
        const response = await axios.post('http://localhost:8057/saving/getAll', this.formData);
        if (response.data.code === 200) {
          console.log(response)
          this.deposits = response.data.data; // 将返回的数据赋值给 customers
        } else {
          console.error('数据获取失败:', response.data.msg);
        }
      } catch (error) {
        console.error('接口请求失败:', error);
      }
    },
    searchDeposits() {
      // 搜索逻辑已在computed中实现
    },
    editDeposit(deposit) {
      console.log(deposit)
      this.formData.savingID = deposit.savingID
      console.log(deposit.savingID)
      this.depositForm = { ...deposit }
      this.showEditModal = true
    },
    
    async deleteDeposit(id) {
        this.formData.savingID = id
      if (confirm('确定要删除这个存款业务吗？')) {
        try {
          const response = await axios.post('http://localhost:8057/saving/delete', this.formData);
          if (response.data.code === 200) {
            console.log(response)
            alert(response.data.msg)
          } else {
            alert(response.data.msg)
            console.error('数据获取失败:', response.data.msg);
          }
        } catch (error) {
          console.error('接口请求失败:', error);
        }
      }
    },
    
    toggleStatus(deposit) {
      const newStatus = deposit.status === 'active' ? 'inactive' : 'active'
      const action = newStatus === 'active' ? '启用' : '停用'
      
      if (confirm(`确定要${action}这个存款业务吗？`)) {
        const index = this.deposits.findIndex(d => d.id === deposit.id)
        if (index !== -1) {
          this.deposits[index].status = newStatus
        }
        alert(`存款业务${action}成功！`)
      }
    },
    
    async saveDeposit() {
      this.formData.savingName = this.depositForm.name
      this.formData.descrip = this.depositForm.description

      if (this.showEditModal) {
        // 编辑存款业务
        try {
          const response = await axios.post('http://localhost:8057/saving/update', this.formData);
          if (response.data.code === 200) {
            console.log(response)
            alert(response.data.msg)
          } else {
            alert(response.data.msg)
            console.error('数据获取失败:', response.data.msg);
          }
        } catch (error) {
          console.error('接口请求失败:', error);
        }
      } else {
       try {
          const response = await axios.post('http://localhost:8057/saving/create', this.formData);
          if (response.data.code === 200) {
            console.log(response)
            alert(response.data.msg)
          } else {
            alert(response.data.msg)
            console.error('数据获取失败:', response.data.msg);
          }
        } catch (error) {
          console.error('接口请求失败:', error);
        }
      }
      this.closeModal()
    },
    
    closeModal() {
      this.showAddModal = false
      this.showEditModal = false
      this.depositForm = {
        name: '',
        description: '',
        interestRate: '',
        minAmount: '',
        status: 'active'
      }
      this.editingId = null
    },
    
    exportToCSV() {
      const headers = ['业务类型编号', '业务名称', '描述']
      const csvContent = [
        headers.join(','),
        ...this.filteredDeposits.map(deposit => [
          deposit.savingID,
          deposit.savingName,
          deposit.descrip,
        ].join(','))
      ].join('\n')
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `存款业务数据_${new Date().toISOString().split('T')[0]}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      alert('存款业务数据导出成功！')
    }
  }
}
</script>

<style scoped>
.deposit-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background: #2563eb;
  color: white;
}

.btn-primary:hover {
  background: #1d4ed8;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background: #4b5563;
}

.btn-icon {
  font-size: 16px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-box {
  display: flex;
  flex: 1;
  max-width: 400px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px 0 0 6px;
  font-size: 14px;
}

.search-btn {
  padding: 10px 16px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
}

.filter-select {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.data-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.data-table td {
  font-size: 14px;
  color: #1f2937;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #dcfce7;
  color: #166534;
}

.status-badge.inactive {
  background: #fef2f2;
  color: #dc2626;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-icon-btn {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.btn-icon-btn:hover {
  background: #f3f4f6;
}

.btn-icon-btn.delete:hover {
  background: #fef2f2;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #6b7280;
}

.modal-form {
  padding: 24px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #2563eb;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.range-input {
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  width: 140px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 12px;
  }
}
</style> 